import http from '@ohos.net.http';
import { ApiResponse } from '../types';

export interface RequestConfig {
  method: 'GET' | 'POST' | 'PUT' | 'DELETE';
  url: string;
  data?: any;
  headers?: Record<string, string>;
  timeout?: number;
}

export class HttpClient {
  private baseURL: string;
  private defaultTimeout: number = 30000;
  private defaultHeaders: Record<string, string> = {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  };

  constructor(baseURL: string = 'http://localhost:3000/api/v1') {
    this.baseURL = baseURL;
  }

  public async request<T = any>(config: RequestConfig): Promise<ApiResponse<T>> {
    const httpRequest = http.createHttp();
    
    try {
      const url = config.url.startsWith('http') ? config.url : `${this.baseURL}${config.url}`;
      
      const headers = {
        ...this.defaultHeaders,
        ...config.headers
      };

      // 添加认证token
      const token = await this.getAuthToken();
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const requestOptions: http.HttpRequestOptions = {
        method: config.method,
        header: headers,
        connectTimeout: config.timeout || this.defaultTimeout,
        readTimeout: config.timeout || this.defaultTimeout
      };

      if (config.data && (config.method === 'POST' || config.method === 'PUT')) {
        requestOptions.extraData = JSON.stringify(config.data);
      }

      const response = await httpRequest.request(url, requestOptions);
      
      if (response.responseCode >= 200 && response.responseCode < 300) {
        const data = JSON.parse(response.result as string);
        return {
          success: true,
          data: data.data,
          message: data.message
        };
      } else {
        const errorData = JSON.parse(response.result as string);
        return {
          success: false,
          message: errorData.message || 'Request failed',
          error: errorData.error,
          code: response.responseCode
        };
      }
    } catch (error) {
      console.error('HTTP request failed:', error);
      return {
        success: false,
        message: '网络请求失败，请检查网络连接',
        error: error.message
      };
    } finally {
      httpRequest.destroy();
    }
  }

  public async get<T = any>(url: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'GET',
      url,
      headers
    });
  }

  public async post<T = any>(url: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'POST',
      url,
      data,
      headers
    });
  }

  public async put<T = any>(url: string, data?: any, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'PUT',
      url,
      data,
      headers
    });
  }

  public async delete<T = any>(url: string, headers?: Record<string, string>): Promise<ApiResponse<T>> {
    return this.request<T>({
      method: 'DELETE',
      url,
      headers
    });
  }

  private async getAuthToken(): Promise<string | null> {
    try {
      const preferences = globalThis.abilityContext.getPreferences('auth_prefs');
      const token = await preferences.get('auth_token', '');
      return token as string || null;
    } catch (error) {
      console.error('Failed to get auth token:', error);
      return null;
    }
  }

  public setBaseURL(baseURL: string): void {
    this.baseURL = baseURL;
  }

  public setTimeout(timeout: number): void {
    this.defaultTimeout = timeout;
  }

  public setDefaultHeaders(headers: Record<string, string>): void {
    this.defaultHeaders = { ...this.defaultHeaders, ...headers };
  }
}